package com.chrilwe.pigpig.auth.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;

import com.chrilwe.pigpig.auth.client.UserClient;
import com.chrilwe.pigpig.auth.config.UserJwt;

import cn.chrilwe.pigpig.core.model.user.Authority;
import cn.chrilwe.pigpig.core.model.user.ext.UserExt;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Autowired
	private UserClient userClient;
	
	@Autowired
	private ClientDetailsService clientDetailsService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 取出身份，如果身份为空说明没有认证
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		// 没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
		if (authentication == null) {
			ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
			if (clientDetails != null) {
				// 密码
				String clientSecret = clientDetails.getClientSecret();
				return new User(username, clientSecret, AuthorityUtils.commaSeparatedStringToAuthorityList(""));
			}
		}
		
		UserExt userExt = userClient.queryByUserName(username);
		if(userExt == null) {
			return null;
		}
		
		List<Authority> authorities = userExt.getAuthorities();
		String str = "";
		if(authorities != null && authorities.size() > 0) {
			for(int i = 0; i < authorities.size(); i++) {
				if(i == authorities.size() - 1)
					str += authorities.get(i).getName();
				else
					str += authorities.get(i).getName() + ",";
			}
		}
		
		UserJwt userJwt = new UserJwt(username,userExt.getUser().getPassword(),AuthorityUtils.commaSeparatedStringToAuthorityList(str));
		return userJwt;
	}
}
